import React, { useState, useCallback, useEffect, useRef } from "react";
import ChatBox from "./components/ChatBox";
import SendMessage from "./components/SendMessage";
import { Input, Spin, message } from 'antd';

const { Search } = Input;
const ws = new WebSocket("ws://127.0.0.1:8060");

const Chat: React.FC = () => {

    const [chatlist, setChatList] = useState<any>([]);
    const [user, setUser] = useState<any>({});

    useEffect(() => {

        ws.onopen = (e) => {
            console.log(e);
            ws.send(
                JSON.stringify({ uid: users.id })
            );
        }
        const users = JSON.parse(
            window.localStorage.getItem("user") || "{}"
        );
        setUser(users);



        ws.onmessage = (e) => {
            console.log("后台推送：", JSON.parse(e.data));
            setChatList((chatlist: any) => [
                ...chatlist,
                JSON.parse(e.data)
            ]);
        };

        ws.onclose = () => {
            console.log("websocket连接关闭...")
        };
        ws.onerror = (err: any) => {
            console.log(err)
        }

    }, [])





    const onSend = useCallback((val: any) => {

        ws.send(
            JSON.stringify(val)
        );
        setChatList((chatlist: any) => [
            ...chatlist,
            val
        ]);

    }, []);

    const onSendPic = useCallback((val: any) => {
        console.log(val);

        ws.send(
            JSON.stringify(val)
        );
        setChatList((chatlist: any) => [
            ...chatlist,
            val
        ]);

    }, []);


    return (
        <div className="chat">
            <ChatBox id={user.id} fid={user.receive_id} chatlist={chatlist} />
            <SendMessage onSendPic={onSendPic} user={user} onSend={onSend} />
        </div>
    )
}
export default Chat;